package com.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shop.mapper.UserMapper;
import com.shop.pojo.User;
import com.shop.service.UserService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public User findUserName(String username) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username",username);
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    public void add(User user) {
        BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();
        String password=bCryptPasswordEncoder.encode(user.getPassword());
        user.setPassword(password);
        userMapper.insert(user);
    }

    @Override
    public Page<User> pageQuery(Integer pagenum, Integer pageSize, String pageQuery) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        Page<User> page = new Page<>(pagenum,pageSize);
        if (pageQuery!=null&&pageQuery.length()>0){
            wrapper.like("user_id",pageQuery).or().like("username",pageQuery);
            page = userMapper.selectPage(page,wrapper);
        }else{
            page = userMapper.selectPage(page,null);
        }
        return page;
    }

    @Override
    public void deleteById(Integer id) {
        long count = userMapper.findCountByUserId(id);
        if (count>0){
            new RuntimeException();
        }
        userMapper.deleteById(id);
    }

    @Override
    public void edit(User user) {
        userMapper.updateById(user);
    }

    @Override
    public User findById(Integer id) {
        return userMapper.selectById(id);
    }

    @Override
    public List<User> findAll() {
        return userMapper.selectList(null);
    }

    @Override
    public User findByUsername(String username) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        User user = userMapper.selectOne(wrapper);
        if (user==null){
            return null;
        }
        return user;
    }

    @Override
    public Integer getUserId(String name) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",name);
        User user = userMapper.selectOne(wrapper);
        return user.getId();
    }
}
